import React, { useState, useContext, useEffect } from 'react';
import { Student } from '../../../shared/models';
import { DataContext } from '../../../shared/DataContext';
import './StudentDetailModal.css';

interface StudentDetailModalProps {
  student: Student | null;
  isOpen: boolean;
  onClose: () => void;
  comments?: Comment[];
  onCommentsChange?: (comments: Comment[]) => void;
}

interface Comment {
  stage: string;
  teacher: string;
  score: string;
  comment: string;
}

const StudentDetailModal: React.FC<StudentDetailModalProps> = ({ student, isOpen, onClose, comments: propComments, onCommentsChange }) => {
  // 从数据上下文获取班级和宿舍信息
  const { classes, dormitories } = useContext(DataContext);
  
  // 评语数据状态 - 使用父组件传入的数据或默认值
  const [comments, setComments] = useState<Comment[]>(propComments || [
    { stage: '专业一', teacher: '张三', score: '90', comment: '' }
    // 可以添加更多默认评语项
  ]);
  
  // 当父组件传入的评语数据变化时更新本地状态
  useEffect(() => {
    if (propComments) {
      setComments(propComments);
    }
  }, [propComments, student?.id]); // 当学生ID变化时也重新初始化评语
  
  // 保存成功提示状态
  const [saveSuccess, setSaveSuccess] = useState(false);
  
  // 跟踪当前聚焦的输入框
  const [focusedField, setFocusedField] = useState<{index: number, field: keyof Comment} | null>(null);
  
  if (!isOpen || !student) return null;

  // 获取班级信息
  const getClassInfo = (classId: string) => {
    const classInfo = classes.find(c => c.id === classId);
    return classInfo ? `${classInfo.academy} ${classInfo.name}` : '班级信息未设置';
  };
  
  // 获取宿舍信息
  const getDormitoryInfo = (dormitoryId: string) => {
    if (!dormitoryId) return '-';
    const dormitoryInfo = dormitories.find(d => d.id === dormitoryId);
    return dormitoryInfo ? `${dormitoryInfo.building}-${dormitoryInfo.roomNumber}` : '-';
  };

  // 处理评语输入变化
  const handleCommentChange = (index: number, field: keyof Comment, value: string) => {
    const updatedComments = [...comments];
    updatedComments[index][field] = value;
    setComments(updatedComments);
  };
  
  // 添加新的评语项
  const addComment = () => {
    setComments([...comments, { 
      stage: '', 
      teacher: '', 
      score: '', 
      comment: '' 
    }]);
  };
  
  // 保存评语
  const handleSave = () => {
    // 这里可以添加保存到后端的逻辑
    console.log('保存评语:', comments);
    
    // 通知父组件更新评语数据，实现持久化
    if (onCommentsChange) {
      onCommentsChange(comments);
    }
    
    // 显示保存成功提示
    setSaveSuccess(true);
    
    // 3秒后隐藏提示
    setTimeout(() => {
      setSaveSuccess(false);
    }, 3000);
  };

  // 关闭模态框的处理函数
  const handleClose = () => {
    onClose();
  };

  // 点击背景关闭模态框
  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      handleClose();
    }
  };

  // 处理ESC键关闭
  React.useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        handleClose();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [isOpen]);

  return (
    <div className="modal-backdrop" onClick={handleBackdropClick}>
      <div className="modal-content student-comment-modal">
        <div className="modal-header">
          <h2>学生评语</h2>
          <button className="close-btn" onClick={handleClose}>
            ×
          </button>
        </div>
        
        <div className="modal-body">
          {/* 学生姓名标题 */}
          <div className="student-name-header">
            <h1>{student.name}</h1>
          </div>
          
          {/* 基本情况区域 */}
          <div className="basic-info-section">
            <h3>基本情况</h3>
            <div className="basic-info-content">
              <div className="info-row">
                <span>学号：{student.studentId}</span>
              </div>
              <div className="info-row">
                <span>班级：{getClassInfo(student.classId)}</span>
              </div>
              <div className="info-row">
                <span>性别：{student.gender === 'male' ? '男' : '女'}</span>
              </div>
              <div className="info-row">
                <span>联系电话：{student.phoneNumber || '-'}</span>
              </div>
              <div className="info-row">
                <span>宿舍：{getDormitoryInfo(student.dormitoryId || '')}</span>
              </div>
              <div className="info-row">
                <span>家庭地址：{student.address || '-'}</span>
              </div>
            </div>
          </div>
          
          {/* 各阶段评语区域 */}
          <div className="comments-section">
            <h3>各阶段评语</h3>
            <div className="comments-table">
              <div className="comments-header">
                <div className="comment-cell">阶段</div>
                <div className="comment-cell">讲师</div>
                <div className="comment-cell">成绩</div>
                <div className="comment-cell">评语</div>
              </div>
              
              {comments.map((comment, index) => (
                <div key={index} className="comment-row">
                  <div className="comment-cell">
                    {focusedField?.index === index && focusedField?.field === 'stage' ? (
                      <input
                        type="text"
                        value={comment.stage}
                        onChange={(e) => handleCommentChange(index, 'stage', e.target.value)}
                        onBlur={() => setFocusedField(null)}
                        className="comment-input"
                        placeholder="请输入阶段名称"
                        autoFocus
                      />
                    ) : (
                      <div 
                        className="comment-text-display"
                        data-placeholder="点击输入阶段"
                        onClick={() => setFocusedField({index, field: 'stage'})}
                      >
                        {comment.stage}
                      </div>
                    )}
                  </div>
                  <div className="comment-cell">
                    {focusedField?.index === index && focusedField?.field === 'teacher' ? (
                      <input
                        type="text"
                        value={comment.teacher}
                        onChange={(e) => handleCommentChange(index, 'teacher', e.target.value)}
                        onBlur={() => setFocusedField(null)}
                        className="comment-input"
                        placeholder="请输入讲师"
                        autoFocus
                      />
                    ) : (
                      <div 
                        className="comment-text-display"
                        data-placeholder="点击输入讲师"
                        onClick={() => setFocusedField({index, field: 'teacher'})}
                      >
                        {comment.teacher}
                      </div>
                    )}
                  </div>
                  <div className="comment-cell">
                    {focusedField?.index === index && focusedField?.field === 'score' ? (
                      <input
                        type="text"
                        value={comment.score}
                        onChange={(e) => handleCommentChange(index, 'score', e.target.value)}
                        onBlur={() => setFocusedField(null)}
                        className="comment-input"
                        placeholder="请输入成绩"
                        autoFocus
                      />
                    ) : (
                      <div 
                        className="comment-text-display"
                        data-placeholder="点击输入成绩"
                        onClick={() => setFocusedField({index, field: 'score'})}
                      >
                        {comment.score}
                      </div>
                    )}
                  </div>
                  <div className="comment-cell">
                    {focusedField?.index === index && focusedField?.field === 'comment' ? (
                      <textarea
                        value={comment.comment}
                        onChange={(e) => handleCommentChange(index, 'comment', e.target.value)}
                        onBlur={() => setFocusedField(null)}
                        className="comment-textarea"
                        rows={3}
                        placeholder="请输入评语..."
                        autoFocus
                      />
                    ) : (
                      <div 
                        className="comment-text-display"
                        data-placeholder="点击输入评语"
                        onClick={() => setFocusedField({index, field: 'comment'})}
                      >
                        {comment.comment}
                      </div>
                    )}
                  </div>
                </div>
              ))}
              
              {/* 添加新评语按钮 */}
              <button className="add-comment-btn" onClick={addComment}>
                +
              </button>
            </div>
          </div>
        </div>
        
        {/* 保存按钮 */}
        <div className="modal-footer">
          <button className="save-btn" onClick={handleSave}>
            保存
          </button>
        </div>
        
        {/* 保存成功提示 */}
        {saveSuccess && (
          <div className="save-success-toast">
            保存成功
          </div>
        )}
      </div>
    </div>
  );
};

export default StudentDetailModal;